<template>
  <div class="records-view">
    <div class="page-header">
      <h2>记录查看</h2>
      <div class="header-controls">
        <div class="records-filter">
          <button 
            :class="{ active: recordType === 'qa' }"
            @click="recordType = 'qa'"
          >
            答疑记录
          </button>
          <button 
            :class="{ active: recordType === 'appointment' }"
            @click="recordType = 'appointment'"
          >
            预约记录
          </button>
        </div>
        
        <div class="time-filter">
          <el-select 
            v-model="selectedTimeRange" 
            placeholder="选择时段" 
            @change="handleTimeRangeChange"
            style="width: 200px;"
          >
            <el-option label="全部时段" value="all" />
            <el-option label="今天" value="today" />
            <el-option label="最近7天" value="7days" />
            <el-option label="最近30天" value="30days" />
            <el-option label="自定义时段" value="custom" />
          </el-select>
          
          <el-date-picker
            v-if="selectedTimeRange === 'custom'"
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="margin-left: 10px; width: 300px;"
            placement="bottom-end"
          />
        </div>
      </div>
    </div>

    <!-- 答疑记录 -->
    <div v-if="recordType === 'qa'" class="qa-records">
      <div class="records-list">
        <div 
          v-for="record in filteredQARecords" 
          :key="record.id" 
          class="record-card"
        >
          <div class="record-header">
            <div class="farmer-info">
              <h3>{{ record.farmerName }}</h3>
              <span class="record-date">{{ record.date }}</span>
            </div>
            <div class="record-duration">
              时长: {{ formatDuration(record.duration) }}
            </div>
          </div>
          
          <div class="record-preview">
            <div class="preview-messages">
              <div 
                v-for="message in record.previewMessages" 
                :key="message.id"
                class="preview-message"
                :class="message.sender"
              >
                <span class="message-text">{{ message.content }}</span>
              </div>
            </div>
          </div>
          
          <div class="record-actions">
            <el-button type="primary" @click="viewQADetail(record.id)">
              <i class="fas fa-eye"></i> 查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约记录 -->
    <div v-else class="appointment-records">
      <div class="records-list">
        <div 
          v-for="record in filteredAppointmentRecords" 
          :key="record.id" 
          class="record-card"
          :class="record.status"
        >
          <div class="record-header">
            <div class="farmer-info">
              <h3>{{ record.farmerName }}</h3>
              <span class="record-date">{{ record.date }}</span>
            </div>
            <div class="record-status" :class="record.status">
              {{ getStatusText(record.status) }}
            </div>
          </div>
          
          <div class="record-details">
            <div class="detail-item">
              <span class="label">类型：</span>
              <span class="value">{{ record.type === 'online' ? '线上答疑' : '线下预约' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">问题：</span>
              <span class="value">{{ record.problem }}</span>
            </div>
            <div v-if="record.type === 'online'" class="detail-item">
              <span class="label">预约时间：</span>
              <span class="value">{{ record.appointmentTime }}</span>
            </div>
            <div v-if="record.type === 'offline'" class="detail-item">
              <span class="label">地点：</span>
              <span class="value">{{ record.location }}</span>
            </div>
            <div v-if="record.status === 'rejected' && record.rejectReason" class="detail-item">
              <span class="label">拒绝原因：</span>
              <span class="value reject-reason">{{ record.rejectReason }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="currentRecords.length === 0" class="empty-state">
      <div class="empty-icon" v-if="recordType === 'qa'">💬</div>
      <div class="empty-icon" v-else>📅</div>
      <h3>暂无{{ recordType === 'qa' ? '答疑' : '预约' }}记录</h3>
    </div>

    <!-- 答疑详情弹窗 -->
    <el-dialog
      v-model="showQADetail"
      :title="`答疑详情 - ${currentQARecord.farmerName}`"
      width="80%"
      top="5vh"
      class="qa-detail-dialog"
    >
      <div class="qa-detail-content">
        <div class="session-info">
          <div class="info-item">
            <span class="label">农户姓名：</span>
            <span class="value">{{ currentQARecord.farmerName }}</span>
          </div>
          <div class="info-item">
            <span class="label">日期：</span>
            <span class="value">{{ currentQARecord.date }}</span>
          </div>
          <div class="info-item">
            <span class="label">时长：</span>
            <span class="value">{{ formatDuration(currentQARecord.duration) }}</span>
          </div>
        </div>
        
        <div class="messages-section">
          <h4>对话记录</h4>
          <div class="messages-container">
            <div 
              v-for="message in currentQARecord.messages" 
              :key="message.id"
              class="message-item"
              :class="message.sender"
            >
              <div class="message-avatar">
                <el-avatar 
                  :size="32" 
                  :src="message.sender === 'farmer' ? farmerAvatar : expertAvatar"
                />
              </div>
              <div class="message-content-wrapper">
                <div class="message-header">
                  <span class="sender-name">{{ message.sender === 'farmer' ? currentQARecord.farmerName : '专家' }}</span>
                  <span class="message-time">{{ message.time }}</span>
                </div>
                <div class="message-content">
                  {{ message.content }}
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="summary-section">
          <h4>问题总结</h4>
          <div class="summary-content">
            <p>主要问题：{{ currentQARecord.summary?.mainIssue || '白粉病防治咨询' }}</p>
            <p>解决方案：{{ currentQARecord.summary?.solution || '使用25%嘧菌酯悬浮剂1500倍液喷雾，注意通风透光' }}</p>
            <p>建议：{{ currentQARecord.summary?.suggestion || '定期检查，及时清除病叶病果' }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showQADetail = false">关闭</el-button>
          <el-button type="primary" @click="exportRecord(currentQARecord)">
            导出记录
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElDialog, ElButton, ElSelect, ElOption, ElDatePicker, ElAvatar } from 'element-plus'

// 响应式数据
const recordType = ref('qa')
const showQADetail = ref(false)
const selectedTimeRange = ref('all')
const customDateRange = ref([])

const currentQARecord = ref({
  id: null,
  farmerName: '',
  date: '',
  duration: 0,
  messages: [],
  summary: {}
})

// 模拟数据
const qaRecords = ref([
  {
    id: 1,
    farmerName: '张农夫',
    date: '2024-01-25 14:30',
    duration: 854,
    previewMessages: [
      { id: 1, sender: 'farmer', content: '我的西红柿最近出现了白粉病...' },
      { id: 2, sender: 'expert', content: '建议使用25%嘧菌酯悬浮剂1500倍液喷雾...' }
    ],
    messages: [
      { id: 1, sender: 'farmer', content: '我的西红柿最近出现了白粉病，请问有什么有效的防治方法吗？', time: '14:30' },
      { id: 2, sender: 'expert', content: '白粉病是西红柿常见的病害。建议使用25%嘧菌酯悬浮剂1500倍液喷雾，每隔7-10天喷一次，连续2-3次。', time: '14:32' },
      { id: 3, sender: 'expert', content: '同时要注意通风透光，避免种植过密，及时清除病叶病果。', time: '14:33' },
      { id: 4, sender: 'farmer', content: '谢谢专家！另外还有蚜虫的问题，应该怎么处理？', time: '14:35' },
      { id: 5, sender: 'expert', content: '蚜虫可以用10%吡虫啉可湿性粉剂2000倍液喷雾防治，注意叶片正反面都要喷到。', time: '14:37' }
    ],
    summary: {
      mainIssue: '西红柿白粉病和蚜虫防治',
      solution: '25%嘧菌酯悬浮剂1500倍液喷雾 + 10%吡虫啉可湿性粉剂2000倍液',
      suggestion: '定期检查，注意通风透光，及时清除病叶病果'
    }
  },
  {
    id: 2,
    farmerName: '李农户',
    date: '2024-01-24 10:00',
    duration: 642,
    previewMessages: [
      { id: 1, sender: 'farmer', content: '黄瓜种植的土壤要求...' },
      { id: 2, sender: 'expert', content: '黄瓜适宜在疏松肥沃的土壤中生长...' }
    ],
    messages: [
      { id: 1, sender: 'farmer', content: '黄瓜种植对土壤有什么具体要求？', time: '10:00' },
      { id: 2, sender: 'expert', content: '黄瓜适宜在疏松肥沃、排水良好的沙壤土中生长，pH值在6.0-6.8之间最佳。', time: '10:02' },
      { id: 3, sender: 'farmer', content: '施肥方面有什么建议？', time: '10:05' },
      { id: 4, sender: 'expert', content: '建议基肥使用腐熟有机肥，追肥以氮磷钾复合肥为主，注意不同生长阶段的营养需求。', time: '10:07' }
    ],
    summary: {
      mainIssue: '黄瓜种植土壤和施肥要求',
      solution: '沙壤土种植，合理施肥管理',
      suggestion: '注意土壤改良和科学施肥'
    }
  },
  {
    id: 3,
    farmerName: '王种植户',
    date: '2024-01-20 09:15',
    duration: 723,
    previewMessages: [
      { id: 1, sender: 'farmer', content: '果树修剪技术咨询...' },
      { id: 2, sender: 'expert', content: '冬季修剪要注意...' }
    ],
    messages: [
      { id: 1, sender: 'farmer', content: '果树冬季修剪有什么注意事项？', time: '09:15' },
      { id: 2, sender: 'expert', content: '冬季修剪要注意保留主干，去除病虫枝、交叉枝，保持树冠通风透光。', time: '09:18' },
      { id: 3, sender: 'farmer', content: '修剪后需要做什么处理？', time: '09:20' },
      { id: 4, sender: 'expert', content: '修剪后要及时涂抹伤口保护剂，防止病菌感染和水分流失。', time: '09:22' }
    ],
    summary: {
      mainIssue: '果树冬季修剪技术',
      solution: '科学修剪，伤口保护',
      suggestion: '定期修剪，注意树形培养'
    }
  }
])

const appointmentRecords = ref([
  {
    id: 1,
    farmerName: '王种植户',
    date: '2024-01-24 10:00',
    type: 'online',
    problem: '黄瓜病虫害防治咨询',
    appointmentTime: '2024-01-24 10:00',
    status: 'accepted'
  },
  {
    id: 2,
    farmerName: '赵农场主',
    date: '2024-01-23 14:45',
    type: 'offline',
    problem: '土壤改良技术现场考察',
    location: '河北省石家庄市',
    status: 'rejected',
    rejectReason: '时间冲突，无法安排'
  },
  {
    id: 3,
    farmerName: '钱农户',
    date: '2024-01-22 09:30',
    type: 'online',
    problem: '果树修剪技术指导',
    appointmentTime: '2024-01-22 09:30',
    status: 'accepted'
  },
  {
    id: 4,
    farmerName: '孙农户',
    date: '2024-01-18 16:20',
    type: 'offline',
    problem: '大棚蔬菜种植技术指导',
    location: '山东省寿光市',
    status: 'accepted'
  }
])

// 头像图片
const farmerAvatar = ref('https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop')
const expertAvatar = ref('https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=100&h=100&fit=crop')

// 计算属性
const currentRecords = computed(() => {
  return recordType.value === 'qa' ? qaRecords.value : appointmentRecords.value
})

const filteredQARecords = computed(() => {
  return filterRecordsByTimeRange(qaRecords.value)
})

const filteredAppointmentRecords = computed(() => {
  return filterRecordsByTimeRange(appointmentRecords.value)
})

// 方法
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}分${secs}秒`
}

const getStatusText = (status) => {
  const statusMap = {
    'accepted': '已接受',
    'rejected': '已拒绝',
    'pending': '待处理'
  }
  return statusMap[status] || '未知状态'
}

const viewQADetail = (recordId) => {
  const record = qaRecords.value.find(r => r.id === recordId)
  if (record) {
    currentQARecord.value = { ...record }
    showQADetail.value = true
  }
}

const handleTimeRangeChange = () => {
  // 当时段选择改变时，可以在这里添加额外的处理逻辑
  console.log('选择的时段:', selectedTimeRange.value)
}

const filterRecordsByTimeRange = (records) => {
  if (selectedTimeRange.value === 'all') {
    return records
  }
  
  const now = new Date()
  let startDate = new Date()
  
  switch (selectedTimeRange.value) {
    case 'today':
      startDate.setHours(0, 0, 0, 0)
      break
    case '7days':
      startDate.setDate(now.getDate() - 7)
      break
    case '30days':
      startDate.setDate(now.getDate() - 30)
      break
    case 'custom':
      if (customDateRange.value && customDateRange.value.length === 2) {
        return records.filter(record => {
          const recordDate = new Date(record.date)
          return recordDate >= customDateRange.value[0] && recordDate <= customDateRange.value[1]
        })
      }
      return records
    default:
      return records
  }
  
  return records.filter(record => {
    const recordDate = new Date(record.date)
    return recordDate >= startDate
  })
}

const exportRecord = (record) => {
  // 导出记录的逻辑
  console.log('导出记录:', record)
  ElMessage.success('记录导出成功')
}

onMounted(() => {
  // 初始化代码
})
</script>

<style scoped>
.records-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.header-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  flex-wrap: wrap;
  gap: 15px;
}

.records-filter {
  display: flex;
  gap: 10px;
}

.records-filter button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.records-filter button.active {
  background: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.time-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.records-list {
  display: grid;
  gap: 20px;
}

.record-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.record-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
}

.record-card.accepted {
  border-left: 4px solid #4CAF50;
}

.record-card.rejected {
  border-left: 4px solid #f44336;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.farmer-info h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.record-date {
  color: #666;
  font-size: 14px;
}

.record-duration, .record-status {
  font-size: 14px;
  color: #666;
}

.record-status.accepted {
  color: #4CAF50;
  font-weight: 600;
}

.record-status.rejected {
  color: #f44336;
  font-weight: 600;
}

/* 答疑记录样式 */
.preview-messages {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.preview-message {
  max-width: 80%;
}

.preview-message.farmer {
  align-self: flex-start;
}

.preview-message.expert {
  align-self: flex-end;
}

.message-text {
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 13px;
  line-height: 1.4;
  display: inline-block;
}

.preview-message.farmer .message-text {
  background: #f1f1f1;
  color: #333;
}

.preview-message.expert .message-text {
  background: #E8F5E9;
  color: #2E7D32;
}

/* 预约记录样式 */
.record-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.label {
  font-weight: 600;
  color: #555;
  min-width: 70px;
}

.value {
  color: #333;
  flex: 1;
}

.reject-reason {
  color: #f44336;
}

.record-actions {
  display: flex;
  justify-content: flex-end;
}

/* 答疑详情样式 */
.qa-detail-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.session-info {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item .label {
  font-size: 12px;
  color: #666;
  min-width: auto;
}

.info-item .value {
  font-weight: 600;
  color: #333;
}

.messages-section {
  margin-bottom: 20px;
}

.messages-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 12px;
}

.message-item.farmer {
  flex-direction: row;
}

.message-item.expert {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content-wrapper {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-item.farmer .message-content-wrapper {
  align-items: flex-start;
}

.message-item.expert .message-content-wrapper {
  align-items: flex-end;
}

.message-header {
  display: flex;
  gap: 10px;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.sender-name {
  font-weight: 600;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-item.farmer .message-content {
  background: #f1f1f1;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-item.expert .message-content {
  background: #E8F5E9;
  color: #2E7D32;
  border-bottom-right-radius: 4px;
}

.summary-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
}

.summary-content {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 6px;
  border-left: 3px solid #4CAF50;
}

.summary-content p {
  margin: 8px 0;
  line-height: 1.5;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-controls {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .time-filter {
    width: 100%;
    justify-content: flex-start;
  }
  
  .session-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .message-content-wrapper {
    max-width: 85%;
  }
}
</style>